<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>账单分析</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <style>
        /* 加载框样式 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            display: none;
        }
        .loading-container {
            background-color: white;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            max-width: 400px;
            width: 90%;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
        }
        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #007bff;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .loading-text {
            font-size: 16px;
            color: #333;
            margin-bottom: 10px;
        }
        .loading-subtext {
            font-size: 14px;
            color: #666;
        }
        .custom-file-input {
            cursor: pointer;
        }

        .custom-file-label {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }

        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            transition: all 0.3s ease;
        }

        .upload-area.dragover {
            border-color: #007bff;
            background-color: #f8f9fa;
        }

        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
        }

        .btn-primary:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }

        .card {
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
<div class="container mt-5">
    <div class="card">
        <div class="card-header bg-primary text-white text-center">
            <h1>账单分析系统</h1>
        </div>
        <div class="card-body">
            <!-- 原有的账单分析功能 -->
            <div class="mb-6">
                <h2 class="text-center mb-4">账单分析</h2>
                <form id="billForm" enctype="multipart/form-data">
                    <div class="mb-4">
                        <label for="file" class="form-label">上传Excel文件</label>
                        <div class="upload-area" id="uploadArea">
                            <input type="file" class="form-control d-none" id="file" name="file" accept=".xlsx">
                            <i class="fas fa-cloud-upload-alt fa-4x mb-2"></i>
                            <p id="fileLabel">点击上传或拖拽文件到此处</p>
                            <small class="text-muted">支持 .xlsx 格式文件</small>
                        </div>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label for="startDate" class="form-label">开始时间</label>
                            <input type="datetime-local" class="form-control" id="startDate" name="startDate">
                        </div>
                        <div class="col-md-6">
                            <label for="endDate" class="form-label">结束时间</label>
                            <input type="datetime-local" class="form-control" id="endDate" name="endDate">
                        </div>
                    </div>

                    <div class="text-center">
                        <button type="submit" class="btn btn-primary btn-lg">分析账单</button>
                    </div>
                </form>
            </div>

            <!-- 新增的主播数据功能 -->
            <div class="border-top pt-6">
                <h2 class="text-center mb-4">获取主播数据</h2>
                <form id="anchorForm" enctype="multipart/form-data">
                    <div class="mb-4">
                        <label for="billFile" class="form-label">上传账单Excel文件</label>
                        <div class="upload-area" id="billFileArea">
                            <input type="file" class="form-control d-none" id="billFile" name="billFile" accept=".xlsx">
                            <i class="fas fa-file-excel fa-4x mb-2"></i>
                            <p id="billFileLabel">点击上传或拖拽文件到此处</p>
                            <small class="text-muted">包含分账明细-正向-团购数据的.xlsx格式文件</small>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label for="conditionFile" class="form-label">上传条件Excel文件</label>
                        <div class="upload-area" id="conditionFileArea">
                            <input type="file" class="form-control d-none" id="conditionFile" name="conditionFile"
                                   accept=".xlsx">
                            <i class="fas fa-file-excel fa-4x mb-2"></i>
                            <p id="conditionFileLabel">点击上传或拖拽文件到此处</p>
                            <small class="text-muted">包含开始时间、结束时间、主播昵称、内容渠道的.xlsx格式文件</small>
                        </div>
                    </div>

                    <div class="text-center">
                        <button type="button" id="getAnchorDataBtn" class="btn btn-primary btn-lg">获取主播数据</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 加载框 -->
<div id="loadingOverlay" class="loading-overlay">
    <div class="loading-container">
        <div class="loading-spinner"></div>
        <div class="loading-text">数据分析中</div>
        <div class="loading-subtext">请耐心等待，结果会自动下载到本地</div>
    </div>
</div>
<!-- 简单的使用说明 -->
<div class="container mt-5 mb-5">
    <div class="card">
        <div class="card-header bg-info text-white">
            <h3>使用说明</h3>
        </div>
        <div class="card-body">
            <h4>账单分析功能：</h4>
            <ol>
                <li>上传包含账单数据的Excel文件</li>
                <li>选择分析的开始时间和结束时间（可选）</li>
                <li>点击"分析账单"按钮</li>
                <li>系统将自动下载分析结果压缩包</li>
            </ol>

            <h4 class="mt-4">获取主播数据功能：</h4>
            <ol>
                <li>上传第一个Excel文件：包含分账明细-正向-团购sheet数据</li>
                <li>上传第二个Excel文件：包含开始时间、结束时间、主播昵称和内容渠道</li>
                <li>点击"获取主播数据"按钮</li>
                <li>
                    系统将根据第二个文件中的条件筛选第一个文件的数据，生成主播在特定时间段内各渠道日销售数量和金额情况的Excel表格
                </li>
            </ol>
        </div>
    </div>
</div>

<script>
    // 账单分析表单的文件上传处理
    document.getElementById('uploadArea').addEventListener('click', function () {
        document.getElementById('file').click();
    });

    document.getElementById('file').addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (file) {
            document.getElementById('fileLabel').textContent = file.name;
        }
    });

    // 账单文件上传区域处理
    document.getElementById('billFileArea').addEventListener('click', function () {
        document.getElementById('billFile').click();
    });

    document.getElementById('billFile').addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (file) {
            document.getElementById('billFileLabel').textContent = file.name;
        }
    });

    // 条件文件上传区域处理
    document.getElementById('conditionFileArea').addEventListener('click', function () {
        document.getElementById('conditionFile').click();
    });

    document.getElementById('conditionFile').addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (file) {
            document.getElementById('conditionFileLabel').textContent = file.name;
        }
    });

    // 拖拽功能
    const uploadAreas = document.querySelectorAll('.upload-area');
    uploadAreas.forEach(area => {
        area.addEventListener('dragover', function (e) {
            e.preventDefault();
            this.classList.add('dragover');
        });

        area.addEventListener('dragleave', function () {
            this.classList.remove('dragover');
        });

        area.addEventListener('drop', function (e) {
            e.preventDefault();
            this.classList.remove('dragover');

            // 根据上传区域确定对应的input元素
            let inputId = '';
            let labelId = '';
            if (this.id === 'uploadArea') {
                inputId = 'file';
                labelId = 'fileLabel';
            } else if (this.id === 'billFileArea') {
                inputId = 'billFile';
                labelId = 'billFileLabel';
            } else if (this.id === 'conditionFileArea') {
                inputId = 'conditionFile';
                labelId = 'conditionFileLabel';
            }

            if (e.dataTransfer.files.length > 0) {
                const file = e.dataTransfer.files[0];
                document.getElementById(inputId).files = e.dataTransfer.files;
                document.getElementById(labelId).textContent = file.name;
            }
        });
    });

    // 账单分析表单提交
    document.getElementById('billForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const file = document.getElementById('file').files[0];
        if (!file) {
            alert('请先上传Excel文件');
            return;
        }
// 显示加载框
        document.getElementById('loadingOverlay').style.display = 'flex';
        const formData = new FormData();
        formData.append('file', file);

        const startDate = document.getElementById('startDate').value;
        const endDate = document.getElementById('endDate').value;

        if (startDate) {
            formData.append('startTime', new Date(startDate).getTime());
        }

        if (endDate) {
            formData.append('endTime', new Date(endDate).getTime());
        }


        fetch('/api/bill/analyze', {
            method: 'POST',
            body: formData
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return Promise.all([response.blob(), response.headers]);
            })
            .then(([blob, headers]) => {
                // 创建下载链接并触发下载
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                // 动态设置文件名 添加时间段
                const startDate = document.getElementById('startDate').value;
                const endDate = document.getElementById('endDate').value;

                let filename = '账单分析结果';

                // 如果用户选择了时间段，将时间段添加到文件名中
                if (startDate || endDate) {
                    let timeRange = '';
                    if (startDate && endDate) {
                        // 格式化开始时间和结束时间，只保留年月日
                        const formatStartDate = startDate.split('T')[0];
                        const formatEndDate = endDate.split('T')[0];
                        timeRange = `_${formatStartDate}_至_${formatEndDate}`;
                    } else if (startDate) {
                        const formatStartDate = startDate.split('T')[0];
                        timeRange = `_从${formatStartDate}开始`;
                    } else {
                        const formatEndDate = endDate.split('T')[0];
                        timeRange = `_至${formatEndDate}结束`;
                    }
                    filename += timeRange;
                }

                a.download = `${filename}.zip`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
            })
            .catch(error => {
                alert("该时间段无数据");
            }).finally(() => {
            // 隐藏加载框，无论成功还是失败
            document.getElementById('loadingOverlay').style.display = 'none';
        });
    });

    // 获取主播数据按钮点击事件
    document.getElementById('getAnchorDataBtn').addEventListener('click', function () {
        const billFile = document.getElementById('billFile').files[0];
        const conditionFile = document.getElementById('conditionFile').files[0];

        if (!billFile) {
            alert('请先上传账单Excel文件');
            return;
        }

        if (!conditionFile) {
            alert('请先上传条件Excel文件');
            return;
        }

        const formData = new FormData();
        formData.append('billFile', billFile);
        formData.append('conditionFile', conditionFile);

        // 显示加载状态
// 显示加载框
        document.getElementById('loadingOverlay').style.display = 'flex';

        fetch('/api/bill/anchor-data', {
            method: 'POST',
            body: formData
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return Promise.all([response.blob(), response.headers]);
            })
            .then(([blob, headers]) => {
                // 创建下载链接并触发下载
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;

                // 获取当前日期时间，用于文件名
                const now = new Date();
                const dateStr = now.getFullYear() + '' +
                    String(now.getMonth() + 1).padStart(2, '0') + '' +
                    String(now.getDate()).padStart(2, '0') + '' +
                    String(now.getHours()).padStart(2, '0') + '' +
                    String(now.getMinutes()).padStart(2, '0');

                a.download = `主播销售数据_${dateStr}.zip`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
            })
            .catch(error => {
                alert("处理数据失败：" + error.message);
            }).finally(() => {
            // 隐藏加载框，无论成功还是失败
            document.getElementById('loadingOverlay').style.display = 'none';
        });
    });
</script>
</body>
</html>
